package com.laogao.lesson016.trace;

import com.alibaba.ttl.TransmittableThreadLocal;
import org.slf4j.MDC;

/**
 * <b>description</b>： Java进阶、性能优化实战案例100讲，微信公众号:程序员恰恰，源码 & 文档 & 技术支持，请加个人微信号：it3306 <br>
 * <b>time</b>：2025/3/3 11:26 <br>
 * <b>author</b>：ready lao_gao
 */
public class TraceUtils {
    public static final String TRACE_ID = "traceId";

    //public static ThreadLocal<String> traceIdThreadLocal = new ThreadLocal<>();
    /**
     * TransmittableThreadLocal 是阿里巴巴开源的一个扩展工具类，专门用于解决异步线程中 ThreadLocal 值传递的问题。它可以在任务提交时自动将父线程的 ThreadLocal 值传递给子线程。
     */
    public static TransmittableThreadLocal<String> traceIdThreadLocal = new TransmittableThreadLocal<>();

    public static String getTraceId() {
        return traceIdThreadLocal.get();
    }

    public static void setTraceId(String traceId) {
        traceIdThreadLocal.set(traceId);
        MDC.put(TRACE_ID, traceId);
    }

    public static void removeTraceId() {
        traceIdThreadLocal.remove();
        MDC.remove(TRACE_ID);
    }
}
